const { src, dest, series, parallel, watch } = require('gulp');
const gulpLess = require('gulp-less');
const guleCleanCss = require('gulp-clean-css');
const gulpRename = require('gulp-rename');
const gulpBabel = require('gulp-babel');
const gulpUglify = require('gulp-uglify');
const gulpImage = require('gulp-imagemin');
const gulpEjs = require('gulp-ejs');
const gulpHtmlClean = require('gulp-htmlclean');
const gulpRm = require('gulp-rm');
const proxy = require('http-proxy-middleware').createProxyMiddleware;
const bs = require('browser-sync').create();
const package = require('./package.json');
const reload = bs.reload;


const style = () => {
    return src('src/styles/*.less')
        .pipe(gulpLess({}))
        .pipe(guleCleanCss())
        .pipe(gulpRename({ extname: '.min.css' }))
        .pipe(dest('dist/styles/'))
}

const script = () => {
    return src('src/scripts/*.js')
        .pipe(gulpBabel())
        .pipe(gulpUglify())
        .pipe(gulpRename({ extname: '.min.js' }))
        .pipe(dest('dist/scripts/'))
}

const image = () => {
    return src('src/images/*')
        .pipe(gulpImage())
        .pipe(dest('dist/images/'))
}

const static = () => {
    return src('static/**/*')
        .pipe(dest('dist/static/'))
}

const template = () => {
    return src('public/*.html')
        .pipe(gulpEjs(package))
        .pipe(gulpHtmlClean())
        .pipe(dest('dist/'))
}

const clean = () => {
    return src('dist/**/*', { read: false })
        .pipe(gulpRm())
}

const build = series(clean, parallel(
    style,
    script,
    image,
    static,
    template,
))

const preview = series(
    build,
    () => bs.init({
        server: {
            baseDir: 'dist',
            middleware: [proxy('/search', {
                target: 'https://gitee.com',
                changeOrigin: true,
            })]
        },
    }),
)

const develop = series(
    build,
    () => {
        watch(['public/**/*', 'src/**/*', 'static/**/*']).on('change', series(build, reload))
        return bs.init({
            server: {
                baseDir: 'dist',
                middleware: [proxy('/search', {
                    target: 'https://gitee.com',
                    changeOrigin: true,
                })]
            },
        })
    }
)

module.exports = {
    style,
    script,
    image,
    static,
    template,
    clean,
    build,
    preview,
    develop,
}